class PomeloDemo {

    /** 初始化一个 Pinus对象 其实也就是 Pomelo对象 的TS版本 */
    private pinus: Pinus = new Pinus();

    /** gate服务器 的地址 */
    private gateServer: { host: string, port: number } = {
        host: "127.0.0.1",
        port: 4000
    }

    /** gate服务器 查询 有空的 connector服务器 的路由 */
    private gateRouteQueryEnter: string = "gate.gateHandler.entry";

    /** 用户id */
    public uid: string = "nero";

    /** 用户所在的房间 */
    public rid: string = "neroRoom"

    /** 运行demo */
    public async run() {


        //请求gate服务器，以获取 connector服务器 地址
        let conAdress = await this.accessGateServer() as { code: number, host: string, port: number };
        console.log("拿到的connector服务器地址：",conAdress);
        if (conAdress.code != 200) {
            console.log("服务器请求失败");
            return;
        }
        
        //监听channel的消息
        this.listenChannel();

        //请求connector服务器的entry路由，以加入聊天室
        let conres = await this.accessConnector(conAdress, "connector.entryHandler.entry");
        console.log("connector服务器返回的channel所有加入用户：",conres);

    }

    /** 访问gate服务器 */
    private accessGateServer() {        
        return new Promise((resolve) => {
            this.pinus.init({
                host: this.gateServer.host,
                port: this.gateServer.port
                // log: true
            }, (res) => {
                // console.log("this.pinus.init.res: ", res);

                this.pinus.request(
                    this.gateRouteQueryEnter,
                    {
                        uid: this.uid
                    },
                    (queryRes) => {
                        // console.log("空余的connector服务器：", queryRes);
                        this.pinus.disconnect();
                        return resolve(queryRes);
                    }
                );
            });
        });

    }

    /** 访问connector服务器 
     * @param conAdress connector服务器地址
     * @param router 要访问的路由
    */
    private accessConnector(conAdress: { host: string, port: number }, router: string) {
        return new Promise((resolve) => {
            this.pinus.init({
                host: conAdress.host,
                port: conAdress.port
                // log: true
            }, (res) => {
                // console.log("this.pinus.init.res: ", res);

                this.pinus.request(
                    router,
                    {
                        rid: this.rid,
                        username:this.uid
                    },
                    (queryRes) => {
                        // console.log("空余的connector服务器：", queryRes);
                        return resolve(queryRes);
                    }
                );
            });
        });
    }

    /** 监听服务器的channel消息 */
    private listenChannel(){
        this.pinus.on("onAdd",(data)=>{
            console.log("监听到的消息：",data);
        })
    }

}